const fs = require('fs');
const fse = require('fs-extra');
const sass = require('sass');

const fileMap = [
  {
    file: 'projects/components/src/style/index.scss',
    cssDest: 'projects/components/src/aui.min.css',
    targetName: 'aui',
  },
  {
    file: 'projects/components/src/style/index-dark.scss',
    cssDest: 'projects/components/src/aui-dark.min.css',
    targetName: 'aui-dark',
  },
];
fileMap.forEach((item) => {
  buildCss(item.file, item.cssDest, item.targetName, copy);
});

function buildCss(file, cssDest, targetName, callback) {
  sass.render(
    {
      file,
      outputStyle: 'compressed',
    },
    (err, result) => {
      if (!err) {
        let cssStr = result.css.toString('utf8');
        cssStr = relativeUrl(cssStr);
        fs.writeFileSync(cssDest, cssStr);
        callback && callback(cssDest, targetName);
      } else {
        // eslint-disable-next-line
        console.log(err);
      }
    },
  );
}

function relativeUrl(str) {
  return str.replace(/~\/assets\/live/g, '.');
}

function copy(cssDest, targetName) {
  const assetsSrc = 'projects/components/src/style/assets';
  const assetsDest = `${__dirname}/../dist/assets`;

  // 拷贝assets
  fse.copySync(assetsSrc, assetsDest);
  // eslint-disable-next-line no-console
  console.log('静态资源拷贝成功');

  // 拷贝css
  fs.renameSync(cssDest, `${assetsDest}/${targetName}.min.css`);
  // eslint-disable-next-line no-console
  console.log('css build成功');
}
